/*
 * @(#) UserInfoDaoImpl.java 1.0  2011-8-5 
 *
 * (c) Copyright 2011 smshen S3H3L3
 *
 * FILENAME    : UserInfoDaoImpl.java
 * PACKAGE     : com.sm.dao.impl
 * CREATE DATE : 2011-8-5
 * AUTHOR      : smshen
 */

package com.sm.dao.impl;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.sm.dao.UserInfoDao;
import com.sm.model.UserInfo;
import com.sm.util.DataGrid;
import com.sm.util.JsonUtil;


/*******************************************************************************
 *  #(c) smshen S3H3L3 
 *
 *  功能说明: 
  
 *  2011-8-5 下午1:40:07 smshen 创建文件
 * 
 *  修改说明: 创建文件

 *  2011-8-5 下午1:40:07 smshen 修改文件
 * 
 ******************************************************************************/

public class UserInfoDaoImpl extends HibernateDaoSupport implements UserInfoDao {
	
	@Override
	public UserInfo getUserInfoById(String id) {
		return (UserInfo) getSession().get(UserInfo.class, Integer.valueOf(id));
	}

	@Override
	public UserInfo findUserInfoByNameAndPasswd(String userName, String password) {
		String hql = "FROM UserInfo WHERE userName = :userName AND password = :password";
		Query query = getSession().createQuery(hql);
		query.setString("userName", userName);
		query.setString("password", password);
		UserInfo userInfo = query.list().size() > 0 ? (UserInfo) query.list().get(0) : null;
		return userInfo;
	}

	@Override
	public UserInfo checkUserIsExist(String userName) {
		String hql = "FROM UserInfo WHERE userName = :userName";
		Query query = getSession().createQuery(hql);
		query.setString("userName", userName);
		UserInfo userInfo = query.list().size() > 0 ? (UserInfo) query.list().get(0) : null;
		return userInfo;
	}

	@Override
	public void addUser(UserInfo userInfo) {
		getSession().save(userInfo);
	}

	@Override
	public String getAllUserList(HttpServletRequest request) {
		
		DataGrid dataGrid = new DataGrid();
		String page = request.getParameter("page");
		String rows = request.getParameter("rows");
		int indexStart = (Integer.valueOf(page) - 1) * Integer.valueOf(rows);
		String hql = "FROM UserInfo WHERE role = 2";
		Query query = getSession().createQuery(hql);
		dataGrid.setTotal(query.list().size());
		
		query.setFirstResult(indexStart);
		query.setMaxResults(Integer.valueOf(rows));
		dataGrid.setRows(query.list());
		return JsonUtil.object2Json(dataGrid);
	}

	@Override
	public void delUser(String id) {
		getSession().delete(getSession().get(UserInfo.class, Integer.valueOf(id)));
	}

	@Override
	public void updateAndSaveUser(UserInfo userInfo) {
		getSession().update(userInfo);
	}
}


